package org.fuxia.im.core.socket;

import java.io.File;
import java.io.IOException;

import org.fuxia.im.core.ECMessageType;
import org.fuxia.im.core.entries.ECPacket;
import org.fuxia.im.core.listeners.Listener;

public class FilePacketInfoListener implements Listener
{

	public void trigger(Object param)
	{
		ECPacket p = (ECPacket) param;
		switch (ECMessageType.valueOf(p.getMessageType()))
		{
			case FILE_TRANSFER_INFO:
				doCreateServer(p);
				break;
			case FILE_TRANSFER_ACK:
				doStartConnected(p);
				break;
			default:
				break;
		}
	}

	public void doStartConnected(ECPacket p)
	{
		File f = new File("E:\\TDDOWNLOAD\\" + p.getParameter("fileName"));
		if (!f.exists())
		{
			System.out.println("文件不存在" + p.getParameter("fileName"));
			return;
		}
		String hostAddress = p.getParameter("hostAddress");
		int port = Integer.parseInt(p.getParameter("hostPort"));
		FileTransferSocketClient client = FileTransferSocketClient.newInstance(port, hostAddress);
		client.sendFile(f);
	}

	public void doCreateServer(ECPacket p)
	{
		FileTransferScoketServer fc = null;
		while (fc == null)
		{
			try
			{
				fc = FileTransferScoketServer.newInstance();
			}
			catch (Exception e)
			{
				//e.printStackTrace();
			}
		}
		File file = new File("d:\\test_transfer" + p.getParameter("fileName"));
		if (!file.exists())
		{
			try
			{
				file.createNewFile();
			}
			catch (IOException e)
			{
				e.printStackTrace();
			}
		}
		fc.setFile(file);
		new Thread(fc).start();
		String from = p.getFrom();
		String to = p.getTo();
		p.setFrom(to);
		p.setTo(from);
		p.addParam("hostAddress", fc.getIpAddress());
		p.addParam("hostPort", String.valueOf(fc.getPort()));
		p.setMessageType(ECMessageType.FILE_TRANSFER_ACK.name());
		try
		{
			ECNioClientDemo.client.sendMessage(p);
		}
		catch (Exception e)
		{
			e.printStackTrace();
		}
	}
}
